<?php

namespace app\controller;

use app\BaseController;
use app\common\Snowflake;
use app\controller\Response\TradeAlipayRefundResponse;
use GuzzleHttp\Client;
use think\facade\Db;
use think\facade\Log;
use think\Request;
use think\response\Json;
use GuzzleHttp\Exception\GuzzleException;

class Order extends BaseController
{

    // 订单列表
    public function orderList(Request $request): Json
    {
        try {

            //var_dump(111);die();
            $param = $request->param();

            $page = $param['page'] ?? 1;
            $limit = $param['limit'] ?? 10;

            $map = [];

            //id搜索
            if ($param['id'] ?? "") {
                $map[] = ['to.id', '=', $param['id']];
            }
            //用户账号
            if ($param['mobile_phone'] ?? "") {
                $map[] = ['mu.mobile_phone', '=', $param['mobile_phone']];
            }
            //订单类型
            if ($param['type'] ?? "") {
                $map[] = ['to.type', '=', $param['type']];
            }
            //订单状态
            if ($param['status'] ?? "") {
                $map[] = ['to.status', '=', $param['status']];
            }

            // trade_order
            // todo 下周就开始关联查询订单表

            $dataObj = Db::name('trade_order')
                ->alias('to')
                //关联user
                ->leftJoin('member_user mu', 'to.user_id = mu.id')
                //APPId??? 版本???     价格??  状态??
                ->field("to.id,mu.mobile_phone,to.type,to.trade_amount,to.refund_amount,to.product,status,to.created_at")
                ->where($map)
                ->order('to.created_at', 'desc')
                ->page($page, $limit)
                ->select();

            $dataArr = $dataObj->toArray();
            foreach ($dataArr as $key => $value) {
                $dataArr[$key]['id'] = strval($value['id']);
                $product = json_decode($value['product']);
                $dataArr[$key]['name']  = $product->name ?? "";
                $dataArr[$key]['image']  = $product->image ?? "";
                $dataArr[$key]['price']  = $product->price ?? "";

                //处理 status_desc
                if ($value['status'] == 'CLOSED') {
                    $dataArr[$key]['status_desc'] = '已关闭';
                } elseif ($value['status'] == 'PAID') {
                    $dataArr[$key]['status_desc'] = '已支付';
                } elseif ($value['status'] == 'REFUNDED') {
                    $dataArr[$key]['status_desc'] = '已退款';
                    //当退款金额 < 付款金额 就是部分退款
                    if ($value['trade_amount'] > $value['refund_amount']) {
                        $dataArr[$key]['status_desc'] = '部分退款';
                    }


                } elseif ($value['status'] == 'WAIT_PAY') {
                    $dataArr[$key]['status_desc'] = '待支付';
                } else {
                    $dataArr[$key]['status_desc'] = '未知状态';
                }
            }

            //count
            $count = Db::name('trade_order')
                ->alias('to')
                ->leftJoin('member_user mu', 'to.user_id = mu.id')
                ->field("to.id,mu.mobile_phone,to.type,to.trade_amount,to.product,status,to.created_at")
                ->where($map)
                ->count();

            return json(['code' => 0, 'msg' => 'success', 'data' => ['list' => $dataArr, 'count' => $count]]);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }


    // 订单退款
    public function orderRefund(Request $request): Json{
        try {

            //获取当前操作地址的ip, 公司的ip地址 171.43.188.140
            $ip = $request->ip();

            //这个ip是不在里面返回, 360的是在里面就进去
            //if (!$this->isValidIP($ip)) {
            //    return json(['code' => -1, 'msg' => '非法操作']);
            //}

            $all = $request->all();
            $id = $all['id'] ?? '';                                         // 支付平台的交易号（如果需要的话）
            $channel_order_id = $all['channel_order_id'] ?? '';             // 支付平台的交易号（如果需要的话）

            //$refund_allow = $all['refund_allow'] ?? '';                   // 退款取消
            //if ($refund_allow == 2) {
            //    $res = Db::name("deepseek_trade_order")->where('channel_order_id', $channel_order_id)->update([
            //        'refund_status' => '',
            //        'apply_refund_time' => NULL
            //    ]);
            //    if ($res) {
            //        return json(['code' => 0, 'msg' => '取消退款成功']);
            //    } else {
            //        return json(['code' => -1, 'msg' => '取消退款失败']);
            //    }
            //}

            $password = $all['password'] ?? '';
            if ($password != 'skhd9527') {
                return json(['code' => -1, 'msg' => '密码错误']);
            }

            //如果id存在就用id查订单, 否则 如果$channel_order_id存在, 就用$channel_order_id查订单
            if ($id) {
                $res = Db::name("trade_order")->where('id', $id)->find();
            } elseif ($channel_order_id) {
                $res = Db::name("trade_order")->where('channel_order_id', $channel_order_id)->find();
            } else {
                return json(['code' => -1, 'msg' => '没有找到订单']);
            }

            // if (empty($channel_order_id)) {
            // }

            // 查询订单是否存在

            // 判断订单是否已支付
            if ($res['status'] != "PAID"  && $res['status'] != "REFUNDED") {
                return json(['code' => -1, 'msg' => '订单未支付，无法退款']);
            }

            //如果这个的状态 $res['refund_status'] 是空, 是REFUND_SUCCESS  才能退款
            if ($res['refund_status'] != '' && $res['refund_status'] != 'REFUND_SUCCESS') {
                return json(['code' => -1, 'msg' => '订单处理中, 无法发起退款']);
            }


            if ($all['total_amount'] ?? '') {
                $total_amount = $all['total_amount'];
            } else {
                $total_amount = $res['total_amount'];
            }
            // 生成随机的退款单号
            $out_trade_refund_no = date('YmdHis') . rand(1000, 9999);

            $gateway = new TradeAlipayQrcodeRefundGateway();
            $gateway->setMchNo(Config('key.merchant_no'));
            $gateway->setAppPrivateKey(Config('key.private_key'));
            $gateway->setHwPublicKey(Config('key.merchant_public_key'));
            $gateway->setNotifyUrl('https://steamadmin.spacetime2024.online/index.php/Notify/refund_notify_zzj');

            // 退款请求的参数
            $bizContent = [
                'trade_no' => $res['trade_no'],
                'out_trade_refund_no' => $out_trade_refund_no,         // 商户退款单号
                // ----------------------todo 退款金额 设置 退款处理  删除game 或者清除vip----------------------
                'refund_amount' => $total_amount,
            ];

            // 2.创建远程订单
            /** @var TradeAlipayRefundResponse $response */
            $response = $gateway->refund(['bizContent' => json_encode($bizContent)])->send();

            //var_dump($response->getData());die();
            //判断申请退款是否成功
            if ($response->isSuccessful()) {
                //更新退款状态 refund_status 为申请退款中
                Db::name("trade_order")->where('id', $id)->update([
                    //refund_reason
                    'refund_reason' => $all['refund_reason'] ?? '',
                    //refund_no
                    'refund_no' => $out_trade_refund_no,
                    //refund_amount
                    //'refund_amount' => $total_amount,     退款金额要在回调里处理
                    //退款状态
                    'refund_status' => $response->getData()['refund_status'],
                    //退款时间->在回调里
                    //'refunded_at' => date('Y-m-d H:i:s'),
                    //退款申请时间
                    'apply_refund_time' => date('Y-m-d H:i:s'),
                ]);
                return json(['code' => 0, 'msg' => '正在申请退款']);

            } else {
                // 这里需要记录退款失败的原因
                log::write('退款失败' . json_encode($response->getData()));
                return json(['code' => -1, 'msg' => $response->getData()['sub_msg'] ?? '退款失败']);
            }

        }catch (\Exception $e){
            return json(['code' => -1, 'msg' => $e->getMessage()]);      //可能金额超过, 业务异常

        }

    }


}